import axios from 'axios'
import { BASE_URL, CODE_SUCCESS, CODE_USER_NOT_LOGIN, CODE_LOGIN_EXPIRED, CODE_PERMISSION_DENIED } from '../common_js/common_variable'
// import { useCounterStore } from '@/stores/counter'
import router from '../router/router'
import { ElNotification } from 'element-plus'
import { AUTHORIZATION } from '@/common_js/common_variable'

export function request(config) {
  const instance = axios.create({
    baseURL: BASE_URL,
    timeout: 10000,
  })

  // 2.1.请求拦截的作用
  instance.interceptors.request.use(config => {
    // 如果有token,携带token
    // let token = store.getToken;
    // let token = sessionStorage.getItem(AUTHORIZATION)
    let token = localStorage.getItem(AUTHORIZATION)
    if (token) {
      config.headers.Authorization = token
    }

    return config
  }, err => {
    // console.log(err);
  })

  // 2.2.响应拦截
  instance.interceptors.response.use(res => {
    if (res.headers['refresh-token']) {// token续约！
      console.log('token续约')
    }

    const resData = res.data
    if (resData.code === CODE_PERMISSION_DENIED) {
      ElNotification({
        title: resData.message,
        message: '您的权限不足',
        type: 'warning'
      });
      return Promise.reject(resData);
    }
    if (resData.code === CODE_USER_NOT_LOGIN) {
      ElNotification({
        title: resData.message,
        message: "请先登录",
        type: 'warning'
      });
      router.push('/login');
      return Promise.reject(resData);
    }
    if (resData.code === CODE_LOGIN_EXPIRED) {
      ElNotification({
        title: resData.message,
        message: "您的身份信息已过期，请重新登录",
        type: 'warning'
      });
      router.push('/login');
      return Promise.reject(resData);
    }
    if (resData.code != CODE_SUCCESS) {
      ElNotification({
        title: resData.code,
        message: resData.message,
        type: 'error'
      });
      return Promise.reject(resData);
    }
    return res.data
  }, err => {
    ElNotification({
      title: err.code,
      message: err.message,
      type: 'error'
    });
    return Promise.resolve(err.response);
  })

  return instance(config)
}
